package com.xyhy.core.utils;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

import org.apache.commons.lang3.StringUtils;

public class UrlUtils {

	public static String getUrlParams(String param, String key) {
		return Optional.ofNullable(getUrlParams(param)).map(x -> x.get(key)).orElse(null);
	}

	public static Map<String, String> getUrlParams(String param) {
		Map<String, String> map = new HashMap<String, String>();
		if (StringUtils.isBlank(param)) { return map; }

		String[] params = param.split("&");
		for (int i = 0; i < params.length; i++) {
			String[] p = params[i].split("=");
			if (p.length == 2) {
				map.put(p[0], p[1]);
			}
		}
		return map;
	}

	public static String getUrlParamsByMap(Map<String, Object> map) {
		if (map == null) { return ""; }
		StringBuffer sb = new StringBuffer();
		for (Map.Entry<String, Object> entry : map.entrySet()) {
			sb.append(entry.getKey() + "=" + entry.getValue());
			sb.append("&");
		}
		String s = sb.toString();
		if (s.endsWith("&")) {
			s = StringUtils.substringBeforeLast(s, "&");
		}
		return s;

	}

}
